import { Button, Form, Input, Modal, Pagination, Radio, Table } from 'antd'
import styles from './index.module.scss'
import { useEffect, useState } from 'react'
import { profileAPI } from '@/apis'

export default () => {
  const [loading, setLoading] = useState(false)
  const [data, setData] = useState(() => {
    return {
      keyword: null,
      page: 1,
      size: 20,
      total: 100,
      totalList: [],
      list: [],
      visible: false,
      editVisible: false,
      formData: {
        id: null,
        name: null, // 规则名称
        proportion: null, // 比重
        type: null, // 规则类型
        method: null, // 方式
        minCount: null, // 次数
        maxCount: null, // 最大次数
        score: null, // 得分
      },
      editFormData: {
        id: null,
        name: null, // 规则名称
        proportion: null, // 比重
        type: null, // 规则类型
      },
    }
  })

  const loadData = async () => {
    setLoading(true)
    try {
      const list = await profileAPI.getEnterpriseProfileContent('/enterprise/profile/content')
      data.totalList = list
      loadList()
    } catch (error) {
      console.log('error', error)
    }
    setLoading(false)
  }

  const loadList = () => {
    const filterList = data.totalList.filter((item) => {
      if (data.keyword && item.name.indexOf(data.keyword) === -1) {
        return false
      }
      return true
    })
    data.total = filterList.length
    data.list = filterList.slice((data.page - 1) * data.size, data.page * data.size)
    setData({
      ...data,
    })
  }

  useEffect(() => {
    loadData()
  }, [])

  const openDetailDialog = (row) => {
    const formData = {
      id: row.id,
      name: row.name, // 规则名称
      proportion: row.proportion, // 比重
      type: row.type, // 规则类型
      method: null, // 方式
      minCount: null, // 次数
      maxCount: null, // 最大次数
      score: null, // 得分
    }
    form.setFieldsValue(formData)
    setData({
      ...data,
      visible: true,
      formData,
    })
  }

  const openEditDialog = (row) => {
    const editFormData = {
      id: row.id,
      name: row.name, // 规则名称
      proportion: row.proportion, // 比重
      type: row.type, // 规则类型
    }
    setData({
      ...data,
      editVisible: true,
      editFormData: editFormData,
    })
    editForm.setFieldsValue(editFormData)
  }

  const columns = [
    { title: 'id', width: '50px', dataIndex: 'id', key: 'id' },
    { title: '规则名称', dataIndex: 'name', key: 'name' },
    { title: '比重', dataIndex: 'proportion', key: 'proportion', render: (_, reocrd) => `${reocrd.proportion}%` },
    { title: '统计类型', dataIndex: 'type', key: 'type', render: (_, reocrd) => ['-', '次数', '分值'][reocrd.type] },
    { title: '等级数量', key: 'count', render: (_, record) => `${record.list.length}条 得分区间` },
    {
      title: '操作',
      width: '180px',
      key: 'name',
      render: (_, record) => (
        <>
          <Button size="small" color="default" type="link" onClick={() => openDetailDialog(record)}>
            添加等级
          </Button>
          <Button size="small" color="default" type="link" onClick={() => openEditDialog(record)}>
            编辑
          </Button>
        </>
      ),
    },
  ]

  const handleChangeSize = (page: number, pageSize: number) => {
    ;(data.page = page), (data.size = pageSize)
    setData({
      ...data,
      size: pageSize,
      page: page,
    })
    loadList()
  }

  const handleChangeVisible = (visible) => {
    setData({
      ...data,
      visible,
    })
  }

  const handleChangeEditVisible = (visible) => {
    setData({
      ...data,
      editVisible: visible,
    })
  }

  const [form] = Form.useForm()
  const handleSubmit = async () => {
    await form.validateFields()
    const formData = form.getFieldsValue()
    const totalList = JSON.parse(JSON.stringify(data.totalList))
    const row = totalList.find((item) => item.id === data.formData.id)
    row.list.push({
      method: formData.method,
      minCount: formData.minCount,
      maxCount: formData.maxCount,
      score: formData.score,
    })
    await profileAPI.saveEnterpriseProfileContent('/enterprise/profile/content', totalList)
    data.totalList = totalList
    data.visible = false
    setData(data)
    loadList()
  }

  const [editForm] = Form.useForm()
  const handleEditSubmit = async () => {
    await editForm.validateFields()
    const formData = editForm.getFieldsValue()
    const totalList = JSON.parse(JSON.stringify(data.totalList))
    const row = totalList.find((item) => item.id === data.editFormData.id)
    row.type = formData.type
    row.proportion = formData.proportion
    await profileAPI.saveEnterpriseProfileContent('/enterprise/profile/content', totalList)
    data.totalList = totalList
    data.editVisible = false
    data.editFormData = {
      id: data.editFormData.id,
      name: data.editFormData.name, // 规则名称
      proportion: formData.proportion, // 比重
      type: formData.type, // 规则类型
    }
    setData(data)
    loadList()
  }

  return (
    <div className={styles.page}>
      <div className={styles.header}>
        <div className={styles.title}>园区画像评估规则内容</div>
      </div>
      <div className={styles.table}>
        <Table loading={loading} columns={columns} dataSource={data.list} pagination={false} rowKey="id" />
      </div>
      <div className={styles.paging}>
        <Pagination
          current={data.page}
          total={data.total}
          pageSize={data.size}
          showSizeChanger
          onChange={handleChangeSize}
        />
      </div>
      <Modal
        title="园区画像评估规则-添加等级"
        open={data.visible}
        onCancel={() => handleChangeVisible(false)}
        onOk={() => handleSubmit()}
        okText="保存"
        cancelText="取消"
        footer={(_, { OkBtn, CancelBtn }) => (
          <>
            <CancelBtn />
            <OkBtn />
          </>
        )}
      >
        <Form form={form} labelCol={{ span: 6 }} style={{ maxWidth: 600, padding: 20 }} labelAlign="right">
          {JSON.stringify(data.formData)}
          <Form.Item label="规则名称">{data.formData.name}</Form.Item>
          <Form.Item label="比重">{data.formData.proportion + '%'}</Form.Item>
          <Form.Item label="类型">{['-', '次数', '分值'][data.formData.type] || '-'}</Form.Item>
          <Form.Item label="方式" name="method" rules={[{ required: true, message: '请选择方式' }]}>
            <Radio.Group>
              <Radio value={1}>大于</Radio>
              <Radio value={2}>等于</Radio>
              <Radio value={3}>小于</Radio>
              <Radio value={4}>区间</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label={['-', '次', '分'][data.formData.type] + '数'} required shouldUpdate>
            {({ getFieldValue }) => {
              const method = getFieldValue('method')
              if (method !== 4) {
                return (
                  <Form.Item
                    name="minCount"
                    noStyle
                    rules={[
                      () => ({
                        validator(_, value) {
                          return value ? Promise.resolve() : Promise.reject(new Error('请填写'))
                        },
                      }),
                    ]}
                  >
                    <Input style={{ width: 130 }} type="number" min={0} placeholder="请填写数字"></Input>
                  </Form.Item>
                )
              } else {
                return (
                  <>
                    <Form.Item
                      name="minCount"
                      noStyle
                      rules={[
                        () => ({
                          validator(_, value) {
                            return value ? Promise.resolve() : Promise.reject(new Error('请填写'))
                          },
                        }),
                      ]}
                    >
                      <Input style={{ width: 130 }} type="number" min={0} placeholder="请填写数字"></Input>
                    </Form.Item>
                    <span style={{ margin: '0 10px' }}>至</span>
                    <Form.Item
                      name="maxCount"
                      noStyle
                      rules={[
                        () => ({
                          validator(_, value) {
                            return value ? Promise.resolve() : Promise.reject(new Error('请填写'))
                          },
                        }),
                      ]}
                    >
                      <Input style={{ width: 130 }} type="number" min={0} placeholder="请填写数字"></Input>
                    </Form.Item>
                    <span style={{ marginLeft: '10px' }}>{['-', '次', '分'][data.formData.type]}</span>
                  </>
                )
              }
            }}
          </Form.Item>
          <Form.Item label="得分" name="score" rules={[{ required: true, message: '请输入得分' }]}>
            <Input style={{ width: 200 }} type="number" placeholder="请填写数字" addonAfter="分"></Input>
          </Form.Item>
        </Form>
      </Modal>
      <Modal
        title="园区画像评估规则内容-编辑"
        open={data.editVisible}
        onCancel={() => handleChangeEditVisible(false)}
        onOk={() => handleEditSubmit()}
        okText="保存"
        cancelText="取消"
      >
        <Form form={editForm} labelCol={{ span: 6 }} style={{ maxWidth: 500, padding: 20 }} labelAlign="right">
          <Form.Item label="规则名称">{data.editFormData.name}</Form.Item>
          <Form.Item label="比重" name="proportion" rules={[{ required: true, message: '请填写比重' }]}>
            <Input
              style={{ width: 200 }}
              min={0}
              max={100}
              type="number"
              placeholder="请填写数字"
              addonAfter="%"
            ></Input>
          </Form.Item>
          <Form.Item label="类型" name="type" rules={[{ required: true, message: '请选择类型' }]}>
            <Radio.Group>
              <Radio value={1}>次数</Radio>
              <Radio value={2}>分值</Radio>
            </Radio.Group>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}
